package com.itdou.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itdou.reggie.common.R;
import com.itdou.reggie.entity.User;
import com.itdou.reggie.service.EmployeeService;
import com.itdou.reggie.service.UserService;
import com.itdou.reggie.utils.SMSUtils;
import com.itdou.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送短信验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotBlank(phone)){
            //生成验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            System.out.println(code);

            //调用阿里云短信服务完成发送短信
//            SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code);

            //将生成的验证码保存到session
            session.setAttribute(phone,code);
            return R.success("验证码发送成功");
        }
        return R.error("验证码发送失败");
    }

    /**
     * 发移动端用户登录
     * @param map
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        log.info("接收到"+map.toString());

        //获取手机号验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        //从session中获取验证码进行比对
        Object codeInsession = session.getAttribute(phone);
        System.out.println("sessionincode为"+codeInsession);

        //比对成功
        if (codeInsession!=null && codeInsession.equals(code)){
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone,phone);
            User user = userService.getOne(wrapper);
            if (user==null){
                //判断是否新用户，如果是进行注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            return R.success(user);
        }

        return R.error("登录失败");
    }
}
